package dao.impl;

import dao.GoodDao;
import po.Good;
import util.BaseDao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class GoodDaoImpl implements GoodDao {
    @Override
    public List<Good> selectGood(String sql) {
        Connection con;
        PreparedStatement ps;
        ResultSet rs;

        try{
            con= BaseDao.getConnection();
            ps=con.prepareStatement(sql);
            rs=ps.executeQuery();
            List<Good> list = new ArrayList<>();
            while (rs.next()){
                Good good=new Good();
                good.setGoodId(rs.getString("good_id"));
                good.setGoodName(rs.getString("good_name"));
                good.setType(rs.getString("type"));
                good.setCount(rs.getInt("count"));
                good.setCost(rs.getDouble("cost"));

                list.add(good);
            }
            return list;
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public Good getGood(String good_id) {
        Connection con=null;
        PreparedStatement ps=null;
        ResultSet rs=null;

        try{
            con= BaseDao.getConnection();
            String sql="select * from good where good_id=?";
            ps=con.prepareStatement(sql);
            ps.setString(1,good_id);
            rs=ps.executeQuery();
            while(rs.next()){
                Good good =new Good();
                good.setGoodId(rs.getString("good_id"));
                good.setGoodName(rs.getString("good_name"));
                good.setType(rs.getString("type"));
                good.setCount(rs.getInt("count"));
                good.setCost(rs.getDouble("cost"));

                return good;
            }
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            BaseDao.close(con,ps,rs);
        }
        return null;
    }

    @Override
    public void addGood(Good good) {
        String sql="insert into good values(?,?,?,?,?)";
        List<Object> list =new ArrayList<>();
        list.add(good.getGoodId());
        list.add(good.getGoodName());
        list.add(good.getType());
        list.add(good.getCount());
        list.add((good.getCost()));

        BaseDao.addUpdateDelete(sql, list.toArray());
    }

    @Override
    public void updateGood(Good good) {
        String sql="update good set good_name=?,type=?,count=?,cost=? where good_id=?";
        List<Object> list =new ArrayList<>();
        list.add(good.getGoodName());
        list.add(good.getType());
        list.add(good.getCount());
        list.add((good.getCost()));
        list.add(good.getGoodId());

        BaseDao.addUpdateDelete(sql, list.toArray());
    }

}
